package cn.janescott.framework.dubbo.utils;

import cn.janescott.framework.core.exception.MyException;
import cn.janescott.framework.core.exception.MyExceptionEnums;
import cn.janescott.framework.core.utils.JsonUtils;

import static cn.janescott.framework.dubbo.filter.MyExceptionFilter.SEPARATOR;

/**
 * dubbo自定义异常处理
 *
 * @author scott
 * @date 2019/2/26
 * @see cn.janescott.framework.dubbo.filter.MyExceptionFilter
 * @see cn.janescott.framework.core.json.serializer.MyExceptionSerializer
 * @see cn.janescott.framework.core.json.deserializer.MyExceptionDeserializer
 */
public final class MyDubboExceptionUtils {

    public static MyException handle(RuntimeException rt) {
        MyException ex = null;
        /* 异常标记#~#异常序列化#~#异常消息 */
        String rtMessage = rt.getMessage();
        if (rtMessage.contains(SEPARATOR)) {
            int firstIndex = rtMessage.indexOf(SEPARATOR);
            int secondIndex = rtMessage.indexOf(SEPARATOR, firstIndex + SEPARATOR.length());
            if (secondIndex != -1) {
                /* 异常序列化 */
                String exData = rtMessage.substring(firstIndex + SEPARATOR.length(), secondIndex);
                /* 异常消息 */
                String exMsg = rtMessage.substring(secondIndex + SEPARATOR.length());
                /* NOT RuntimeException, for example: BindException */
                if (!exMsg.trim().isEmpty()) {
                    ex = new MyException(exMsg);
                }
                /* RuntimeException, for example: MyException,IllegalArgumentException */
                if (!exData.trim().isEmpty()) {
                    ex = JsonUtils.fromJson(exData, MyException.class);
                }
            }
        } else {
            ex = new MyException(rt);
        }
        if (null == ex) {
            ex = new MyException(MyExceptionEnums.UNKNOWN_EXCEPTION.getMessage());
        }
        return ex;
    }

}
